<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>个人中心</title>
    <!-- 引入 Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <!-- 引入 Font Awesome 图标库 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link href="./css/style.css" rel="stylesheet">
    <link href="./css/tailwind-styles.css" rel="stylesheet">

    <style>
        .form-group label {
            font-weight: bold;
        }
        .submit-btn {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            border: none;
            border-radius: 5px;
            color: white;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .submit-btn:hover {
            background-color: #0056b3;
        }
        .section-item {
            margin-bottom: 20px;
        }
                /* 新增美化样式 */
        .version-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 8px 8px 0 0;
        }
    </style>
    
</head>
<body class="min-h-screen bg-gray-100 flex flex-col items-center">

<div class="container mx-auto p-4 w-full max-w-4xl space-y-8">
    <!-- 个人中心卡片 -->
    <div class="card bg-white p-8 rounded-lg shadow-md w-full space-y-4">
        <div class="version-header p-6">
            <h2 class="text-xl font-bold text-white text-center flex items-center justify-center space-x-2">
                <i class="fas fa-user"></i>
                <span>个人中心</span>
            </h2>
        </div>
        <div id="user-info" class="text-center">
            <p class="text-lg font-semibold">欢迎回来！</p>
            <p id="user-email" class="text-gray-700"></p>
            <p id="user-id" class="text-gray-700"></p>
        </div>

        <div class="button-container flex justify-between">
            <button id="logout-button" class="w-auto bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline flex items-center justify-center space-x-2">
                <i class="fas fa-sign-out-alt"></i>
                <span>退出登录</span>
            </button>
        
            <button id="home-button" class="w-auto bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline flex items-center justify-center space-x-2"
            onclick="location.href='./index.html'">
                <i class="fas fa-home"></i>
                <span>主页</span>
            </button>
        </div>
    </div>

    <!-- 新版更新版本信息卡片 -->
    <div class="card bg-white p-0 rounded-lg shadow-lg w-full">
        <div class="version-header p-6">
            <h2 class="text-xl font-bold text-white text-center flex items-center justify-center space-x-2">
                <i class="fas fa-rocket"></i>
                <span>版本信息更新</span>
            </h2>
        </div>
        <div class="p-6 space-y-4">
            <form id="version-info-form" class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">版本号</label>
                        <input type="text" class="w-full modern-input rounded-lg p-3 border" 
                               placeholder="1.0.0" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">发布日期</label>
                        <input type="date" class="w-full modern-input rounded-lg p-3 border" required>
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">下载链接</label>
                    <input type="url" class="w-full modern-input rounded-lg p-3 border" 
                           placeholder="https://example.com/download" required>
                </div>
                <div id="sections-container" class="space-y-4"></div>
                <!-- 修改按钮的id为add-section -->
                <button type="button" id="add-section" class="gradient-btn py-2 px-4 rounded-lg flex items-center justify-center space-x-2">
                    <i class="fas fa-plus"></i>
                    <span>添加新章节</span>
                </button>
                <button type="submit" class="w-full gradient-btn py-3 px-6 rounded-lg text-lg font-semibold">
                    提交更新
                </button>
            </form>
        </div>
    </div>

    <!-- 并排的双卡片布局 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
        <!-- 更新邮箱卡片 -->
        <div class="card bg-white p-6 rounded-xl shadow-lg hover:shadow-xl transition-shadow">
            <h2 class="text-xl font-bold mb-4 flex items-center space-x-2 text-indigo-600">
                <i class="fas fa-envelope-open-text"></i>
                <span>邮箱设置</span>
            </h2>
            <form id="update-email-form" class="space-y-4">
                <div>
                    <label for="new-email" class="block text-sm font-medium text-gray-700">新邮箱</label>
                    <input type="email" id="new-email" name="new-email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                    <div class="error mt-1 text-red-500 text-sm hidden">请输入有效的邮箱地址</div>
                </div>
                <div>
                    <label for="current-password" class="block text-sm font-medium text-gray-700">当前密码</label>
                    <input type="password" id="current-password" name="current-password" required pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{8,}" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                    <div class="error mt-1 text-red-500 text-sm hidden">密码至少包含一个字母和一个数字，且长度不少于8个字符，支持 - 和 _ 符号</div>
                </div>
                <button type="submit" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline flex items-center justify-center space-x-2">
                    <i class="fas fa-envelope"></i>
                    <span>更新邮箱</span>
                </button>
            </form>
        </div>

        <!-- 修改密码卡片 -->
        <div class="card bg-white p-6 rounded-xl shadow-lg hover:shadow-xl transition-shadow">
            <h2 class="text-xl font-bold mb-4 flex items-center space-x-2 text-purple-600">
                <i class="fas fa-lock"></i>
                <span>密码安全</span>
            </h2>
            <form id="change-password-form" class="space-y-4">
                <div>
                    <label for="old-password" class="block text-sm font-medium text-gray-700">旧密码</label>
                    <input type="password" id="old-password" name="old-password" required pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{8,}" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                    <div class="error mt-1 text-red-500 text-sm hidden">密码至少包含一个字母和一个数字，且长度不少于8个字符，支持 - 和 _ 符号</div>
                </div>
                <div>
                    <label for="new-password" class="block text-sm font-medium text-gray-700">新密码</label>
                    <input type="password" id="new-password" name="new-password" required pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{8,}" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                    <div class="error mt-1 text-red-500 text-sm hidden">密码至少包含一个字母和一个数字，且长度不少于8个字符，支持 - 和 _ 符号</div>
                </div>
                <div>
                    <label for="confirm-new-password" class="block text-sm font-medium text-gray-700">确认新密码</label>
                    <input type="password" id="confirm-new-password" name="confirm-new-password" required pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{8,}" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                    <div class="error mt-1 text-red-500 text-sm hidden">密码至少包含一个字母和一个数字，且长度不少于8个字符，支持 - 和 _ 符号</div>
                </div>
                <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline flex items-center justify-center space-x-2">
                    <i class="fas fa-key"></i>
                    <span>更改密码</span>
                </button>
            </form>
        </div>
    </div>
</div>

<!-- 引入 jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
    let sectionCounter = 1;

    // 获取用户ID并验证是否已登录
    const isLoggedIn = sessionStorage.getItem('isLoggedIn');
    const userId = sessionStorage.getItem('userId');

    if (!isLoggedIn || !userId) {
        alert('请先登录');
        window.location.href = 'login.html';
    } else {
        // 获取用户信息
        $.get(`/api/user/${userId}`, function (response) {
            $('#user-email').text(`邮箱: ${response.email}`);
            $('#user-id').text(`UUID: ${response.id}`);
        }).fail(function () {
            alert('获取用户信息失败，请重试');
            window.location.href = 'login.html';
        });
    }

    // 绑定退出登录按钮的点击事件
    $('#logout-button').on('click', function () {
        sessionStorage.removeItem('isLoggedIn');
        sessionStorage.removeItem('userEmail');
        sessionStorage.removeItem('userId');
        alert('已退出登录');
        window.location.href = 'login.html';
    });

    // 更新邮箱表单提交处理
    $('#update-email-form').on('submit', function (e) {
        e.preventDefault();

        const newEmail = $('#new-email').val();
        const currentPassword = $('#current-password').val();

        let isValid = true;

        // 验证邮箱格式
        if (!validateEmail(newEmail)) {
            showValidationError($('#new-email'));
            isValid = false;
        } else {
            hideValidationError($('#new-email'));
        }

        // 验证密码格式
        if (!validatePassword(currentPassword)) {
            showValidationError($('#current-password'));
            isValid = false;
        } else {
            hideValidationError($('#current-password'));
        }

        // 如果所有字段都有效，则发送请求到服务器
        if (isValid) {
            $.ajax({
                url: '/api/update-email',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ email: newEmail, password: currentPassword }),
                success: function (response) {
                    alert(response.message);
                    // 刷新页面
                    window.location.reload();
                },
                error: function (xhr) {
                    const errorMessage = xhr.responseJSON ? xhr.responseJSON.message : "更新邮箱失败，请重试";
                    alert(errorMessage);
                }
            });
        }
    });

    // 更改密码表单提交处理
    $('#change-password-form').on('submit', function (e) {
        e.preventDefault();

        const oldPassword = $('#old-password').val();
        const newPassword = $('#new-password').val();
        const confirmNewPassword = $('#confirm-new-password').val();

        let isValid = true;

        // 验证旧密码格式
        if (!validatePassword(oldPassword)) {
            showValidationError($('#old-password'));
            isValid = false;
        } else {
            hideValidationError($('#old-password'));
        }

        // 验证新密码格式
        if (!validatePassword(newPassword)) {
            showValidationError($('#new-password'));
            isValid = false;
        } else {
            hideValidationError($('#new-password'));
        }

        // 验证确认新密码格式
        if (!validatePassword(confirmNewPassword)) {
            showValidationError($('#confirm-new-password'));
            isValid = false;
        } else {
            hideValidationError($('#confirm-new-password'));
        }

        // 检查新密码和确认新密码是否一致
        if (newPassword !== confirmNewPassword) {
            showValidationError($('#confirm-new-password'));
            alert('新密码和确认新密码不一致');
            isValid = false;
        } else {
            hideValidationError($('#confirm-new-password'));
        }

        // 如果所有字段都有效，则发送请求到服务器
        if (isValid) {
            $.ajax({
                url: '/api/change-password',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ oldPassword, newPassword }),
                success: function (response) {
                    alert(response.message);
                    // 刷新页面
                    window.location.reload();
                },
                error: function (xhr) {
                    const errorMessage = xhr.responseJSON ? xhr.responseJSON.message : "更改密码失败，请重试";
                    alert(errorMessage);
                }
            });
        }
    });

    // 添加章节代码
    $('#add-section').on('click', function () {
        sectionCounter++;
        const sectionHtml = `
            <div class="section-item space-y-4 p-6 bg-white rounded-lg shadow-md">
                <div>
                    <label for="section-title-${sectionCounter}" class="block text-sm font-medium text-gray-700 mb-2">章节标题</label>
                    <input type="text" 
                        class="w-full bg-gray-50 border border-gray-300 rounded-lg p-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500" 
                        id="section-title-${sectionCounter}" 
                        placeholder="请输入章节标题"
                        required>
                </div>
                <div id="items-container-${sectionCounter}">
                    <div class="item-row space-y-2">
                        <label for="item-${sectionCounter}-1" class="block text-sm font-medium text-gray-700 mb-2">内容描述</label>
                        <textarea class="w-full bg-gray-50 border border-gray-300 rounded-lg p-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500" 
                                id="item-${sectionCounter}-1" 
                                rows="3" 
                                placeholder="请输入详细内容，注意！注意！注意！此内容只是一行，按Enter键换行只是相当于一行内的空格，如果需要多行，请点击下方的“添加新内容描述”按钮"
                                required></textarea>
                    </div>
                </div>
                <button type="button" id="add-item-${sectionCounter}" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline flex items-center justify-center space-x-2 add-item">
                    <i class="fas fa-plus"></i>
                    <span>添加新内容描述</span>
                </button>
                <button type="button" class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline flex items-center justify-center space-x-2 remove-section">
                    <i class="fas fa-trash-alt"></i>
                    <span>移除本章节</span>
                </button>
            </div>
        `;
        $('#sections-container').append(sectionHtml);

        // 重新绑定事件以处理动态添加的按钮
        bindAddItemEvent();
    });

    function bindAddItemEvent() {
        $('.add-item').off('click').on('click', function() {
            const sectionId = this.id.split('-')[2];
            const container = document.getElementById(`items-container-${sectionId}`);
            const itemCount = container.children.length + 1;

            const newItemRow = `
                <div class="item-row space-y-2">
                    <label for="item-${sectionId}-${itemCount}" class="block text-sm font-medium text-gray-700 mb-2">内容描述</label>
                    <textarea class="w-full bg-gray-50 border border-gray-300 rounded-lg p-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500" 
                            id="item-${sectionId}-${itemCount}" 
                            rows="3" 
                            placeholder="请输入详细内容，注意！注意！注意！此内容只是一行，按Enter键换行只是相当于一行内的空格，如果需要多行，请点击下方的“添加新内容描述”按钮"
                            required></textarea>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', newItemRow);
        });
    }

    // 初始绑定事件
    $(document).ready(function() {
        bindAddItemEvent();

        // 移除章节按钮点击事件
        $(document).on('click', '.remove-section', function () {
            $(this).closest('.section-item').remove();
        });
    });

    // 修改版本信息表单提交处理
    $('#version-info-form').on('submit', function (e) {
        e.preventDefault();

        const userId = sessionStorage.getItem('userId');
        if (!userId) {
            alert('用户未登录');
            window.location.href = 'login.html';
            return;
        }

    const version = $(this).find('input[type="text"]').eq(0).val();
    const releaseDate = $(this).find('input[type="date"]').val();
    const downloadUrl = $(this).find('input[type="url"]').val();

    let content = [];
    $('.section-item').each(function () {
        const sectionTitle = $(this).find('input[type="text"]').val();
        const items = [];
        $(this).find('textarea').each(function () {
            items.push($(this).val());
        });
        content.push({ section: sectionTitle, items: items });
    });

    const postData = {
        version: version,
        releaseDate: releaseDate,
        downloadUrl: downloadUrl,
        content: content
    };

    $.ajax({
        url: '/api/update-version-info',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(postData),
        success: function (response) {
            alert('版本信息更新成功');
            $('#version-info-form')[0].reset();
            $('#sections-container').empty();
            sectionCounter = 1;
        },
        error: function (xhr) {
            alert('版本信息更新失败：' + xhr.responseText);
        }
    });
});

    // 显示验证错误
    function showValidationError($input) {
        const $errorDiv = $input.next('.error');
        $errorDiv.removeClass('hidden');
    }

    // 隐藏验证错误
    function hideValidationError($input) {
        const $errorDiv = $input.next('.error');
        $errorDiv.addClass('hidden');
    }

    // 验证字段通用函数
    function validateField($input, validationFunction) {
        const value = $input.val();
        if (!validationFunction(value)) {
            showValidationError($input);
        } else {
            hideValidationError($input);
        }
    }

    // 验证邮箱格式
    function validateEmail(email) {
        const emailPattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
        return emailPattern.test(email);
    }

    // 验证密码格式
    function validatePassword(password) {
        const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{8,}$/;
        return passwordPattern.test(password);
    }
});
</script>

</body>
</html>